<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member extends CI_Controller {

// num of records per page
	private $limit = 10;
  
   function __construct()
   {
      parent::__construct();
      // load library
		$this->load->library(array('table','form_validation'));
		
		// load helper
		$this->load->helper('url');
		
		// load model
		$this->load->model('Member_model','',TRUE);
   }
   	 

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index1()
	{
		 // Write to $title
     // $this->template->write('title', 'Welcome to the Template Library Docs!');
      
      // Write to $content
     // $this->template->write_view('content', 'post');
      
      // Write to $sidebar
     // $this->template->write_view('sidebar', 'common/sidebar');
      
      // Render the template+

    //  $this->template->render();
	}

	function index($offset = 0)
	{
		// offset
		$uri_segment = 3;
		$offset = $this->uri->segment($uri_segment);
		
		// load data
		$Members = $this->Member_model->get_paged_list($this->limit, $offset)->result();
		
		// generate pagination
		$this->load->library('pagination');
		$config['base_url'] = site_url('Member/index/');
 		$config['total_rows'] = $this->Member_model->count_all();
 		$config['per_page'] = $this->limit;
		$config['uri_segment'] = $uri_segment;
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		
		// generate table data
		$this->load->library('table');
		$this->table->set_empty("&nbsp;");
		$this->table->set_heading('No', 'Name', 'Gender', 'Date of Birth (dd-mm-yyyy)', 'Actions');
		$i = 0 + $offset;
		foreach ($Members as $Member)
		{
			$this->table->add_row(++$i, $Member->mem_firstname, strtoupper($Member->mem_lastname)=='M'? 'Male':'Female', date('d-m-Y',strtotime($Member->mem_dob)), 
				anchor('Member/view/'.$Member->mem_id,'view',array('class'=>'view')).' '.
				anchor('Member/update/'.$Member->mem_id,'update',array('class'=>'update')).' '.
				anchor('Member/delete/'.$Member->mem_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this Member?')"))
			);
		}
		$data['table'] = $this->table->generate();
		
		// load view
		$this->load->view('administration/MemberList', $data);
	}
	

	function number_pad($number,$n) {
	return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
	}

	function formatMemberCode($memberId) {
	return "BKWM".$this->number_pad($memberId,5);
	}


	public function notifyMember($memberInfo){

		$this->load->library('email');
		$config["mailtype"]="html";
		$this->email->initialize($config);

		$this->email->from('nirmal.kumar@bkconnect.net', 'Brahma Kumaris - Wings');
		$this->email->to($memberInfo["email"]); 
		$this->email->bcc('sanjiv.gupta@bkconnect.net');
		$this->email->subject('Wings Member - Account Registration - Successful');
		$stringMessage="Dear Member,<br>Thanks for Registering with us";
		$stringMessage.="<br><br>";
		$stringMessage.="Your Provisional Membership No : ".$memberInfo["membercode"] ;
		$stringMessage.="<br><br>Regards";
		$stringMessage.="<br>BK Wings Team";
		$this->email->message($stringMessage);	
		$this->email->send();

		//echo $this->email->print_debugger();

	}



	public function register()
	{
		
		if($_POST){
			$wingSelected=implode(",",$_POST["mem_wings"]);
				
			
		
            $ignoreFields=Array("cmem_password","mem_wings","bkoption","mem_username","mem_password");
            foreach($ignoreFields as $item){	unset($_POST[$item]);}
			$_POST["mem_username"]=$wingSelected;
			//Check Member Exists
			
			$memEmailExists=$this->member_model->isEMailExists($_POST["mem_email"]);
			if(!$memEmailExists){
				$_POST["rec_status"]=1;
				$_POST["rec_created"]=date('Y-m-d H:i:s', time() + 41400);
				
				$this->db->insert('bkw_members', $_POST); 
				$insertedId = $this->db->insert_id();
				$this->session->set_userdata("memberid",$insertedId);
				$this->session->set_userdata("membercode",$this->formatMemberCode($insertedId));
				$memberInfo["membercode"]=$this->formatMemberCode($insertedId);
				$memberInfo["email"]=$_POST["mem_email"];
				$this->notifyMember($memberInfo);
				redirect("member/register?thank=1");
			}
			else{
					//$this->load->model('wing_model','wing');
				$data["wingsList"]=$this->wing_model->getList();
				$data["wingName"]="";
				$data["thank"]=0;
				$this->load->view('header');
				$this->load->view('member/register',$data);
				$this->load->view('footer');

			}			

		}else{


		//$this->load->model('wing_model','wing');
		$data["wingsList"]=$this->wing_model->getList();
		$data["wingName"]="";
		$data["thank"]=0;
		$this->load->view('header');
		$this->load->view('member/register',$data);
		$this->load->view('footer');

		}
	}


	function add()
	{
		// set empty default form field values
		$this->_set_fields();
		// set validation properties
		$this->_set_rules();
		
		// set common properties
		$data['title'] = 'Add new Member';
		$data['message'] = '';
		$data['action'] = site_url('Member/addMember');
		$data['link_back'] = anchor('Member/index/','Back to list of Members',array('class'=>'back'));
	
		// load view
		$this->load->view('administration/MemberEdit', $data);
	}
	
	function addMember()
	{
		// set common properties
		$data['title'] = 'Add new Member';
		$data['action'] = site_url('Member/addMember');
		$data['link_back'] = anchor('Member/index/','Back to list of Members',array('class'=>'back'));
		
		// set empty default form field values
		$this->_set_fields();
		// set validation properties
		$this->_set_rules();
		
		// run validation
		if ($this->form_validation->run() == FALSE)
		{
			$data['message'] = '';
		}
		else
		{
			// save data
			$Member = array('name' => $this->input->post('name'),
							'gender' => $this->input->post('gender'),
							'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
			$id = $this->Member_model->save($Member);
			
			// set user message
			$data['message'] = '<div class="success">add new Member success</div>';
		}
		
		// load view
		$this->load->view('administration/MemberEdit', $data);
	}
	
	function view($id)
	{
		// set common properties
		$data['title'] = 'Member Details';
		$data['link_back'] = anchor('Member/index/','Back to list of Members',array('class'=>'back'));
		
		// get Member details
		$data['Member'] = $this->Member_model->get_by_id($id)->row();
		
		// load view
		$this->load->view('administration/MemberView', $data);
	}
	
	function update($id)
	{
		// set validation properties
		$this->_set_rules();
		
		// prefill form values
		$Member = $this->Member_model->get_by_id($id)->row();
		$this->form_data->id = $id;
		$this->form_data->name = $Member->name;
		$this->form_data->gender = strtoupper($Member->gender);
		$this->form_data->dob = date('d-m-Y',strtotime($Member->dob));
		
		// set common properties
		$data['title'] = 'Update Member';
		$data['message'] = '';
		$data['action'] = site_url('Member/updateMember');
		$data['link_back'] = anchor('Member/index/','Back to list of Members',array('class'=>'back'));
	
		// load view
		$this->load->view('administration/MemberEdit', $data);
	}
	
	function updateMember()
	{
		// set common properties
		$data['title'] = 'Update Member';
		$data['action'] = site_url('Member/updateMember');
		$data['link_back'] = anchor('Member/index/','Back to list of Members',array('class'=>'back'));
		
		// set empty default form field values
		$this->_set_fields();
		// set validation properties
		$this->_set_rules();
		
		// run validation
		if ($this->form_validation->run() == FALSE)
		{
			$data['message'] = '';
		}
		else
		{
			// save data
			$id = $this->input->post('id');
			$Member = array('name' => $this->input->post('name'),
							'gender' => $this->input->post('gender'),
							'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
			$this->Member_model->update($id,$Member);
			
			// set user message
			$data['message'] = '<div class="success">update Member success</div>';
		}
		
		// load view
		$this->load->view('administration/MemberEdit', $data);
	}
	
	function delete($id)
	{
		// delete Member
		$this->Member_model->delete($id);
		
		// redirect to Member list page
		redirect('Member/index/','refresh');
	}
	
	// set empty default form field values
	function _set_fields()
	{
		$this->form_data->id = '';
		$this->form_data->name = '';
		$this->form_data->gender = '';
		$this->form_data->dob = '';
	}
	
	// validation rules
	function _set_rules()
	{
		$this->form_validation->set_rules('name', 'Name', 'trim|required');
		$this->form_validation->set_rules('gender', 'Gender', 'trim|required');
		$this->form_validation->set_rules('dob', 'DoB', 'trim|required|callback_valid_date');
		
		$this->form_validation->set_message('required', '* required');
		$this->form_validation->set_message('isset', '* required');
		$this->form_validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
	}
	
	// date_validation callback
	function valid_date($str)
	{
		//match the format of the date
		if (preg_match ("/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/", $str, $parts))
		{
			//check weather the date is valid of not
			if(checkdate($parts[2],$parts[1],$parts[3]))
				return true;
			else
				return false;
		}
		else
			return false;
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */